package com.keur.money.data.dv.hepler

import com.keur.money.data.dv.utils.stringToZString
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.BatteryManager
import com.google.gson.Gson
import com.keur.money.app.MyApp

/**
 * battery
 */
class DvBatHelper(private val onResult: (String) -> Unit) {
    val context = MyApp.app

    private val batReceiver: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            try {
                val status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1)
                val isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL

                val chargePlug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1)
                val isUsbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB
                val isAcCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC

                val data = batToJson().apply {
                    put("isCharging", if (isCharging) "YES" else "NO")
                    put("isAcCharge", if (isAcCharge) "YES" else "NO")
                    put("isUsbCharge", if (isUsbCharge) "YES" else "NO")
                    put("batteryPct", intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0).toString())
                }

                val result = Gson().toJson(data).trim().stringToZString()
                onResult.invoke(result)
                stop()

            } catch (e: Exception) {
                stop()
            }
        }
    }

    fun start() {
        try {
            val filter = IntentFilter(Intent.ACTION_BATTERY_CHANGED)
            context.registerReceiver(batReceiver, filter)
        } catch (e: Exception) {
            onResult.invoke(Gson().toJson(batToJson()).trim().stringToZString())
        }
    }

    fun stop() {
        try {
            context.unregisterReceiver(batReceiver)
        } catch (e: Exception) {
            //
        }
    }

    private fun batToJson(): HashMap<String, Any> {
        return hashMapOf<String, Any>().apply {
            put("isCharging", "")
            put("isAcCharge", "")
            put("isUsbCharge", "")
            put("batteryPct", "")
        }
    }
}
